package com.freud.logic.business.controller;

import java.util.HashMap;
import java.util.Map;

import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.freud.framework.base.BaseController;
import com.freud.framework.base.BaseRequest;
import com.freud.logic.business.bean.Good;
import com.freud.logic.business.model.GoodCondition;
import com.freud.logic.business.service.DistrictService;
import com.freud.logic.business.service.GoodService;
import com.freud.logic.business.service.RepositoryService;

@Controller
@RequestMapping("/good")
public class GoodController extends BaseController {

	@Autowired
	private GoodService goodService;

	@Autowired
	private RepositoryService repositoryService;

	@Autowired
	private DistrictService districtService;

	@RequestMapping(value = "/index")
	public String index() {
		return "good.index";
	}

	@RequestMapping(value = "/list")
	@ResponseBody
	public Map<String, Object> list(BaseRequest baseRequest,
			GoodCondition condition) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("total", goodService.getAll(buildRowBounds(), condition)
				.size());
		result.put("rows",
				goodService.getAll(buildRowBounds(baseRequest), condition));
		return result;
	}

	@RequestMapping(value = "/add")
	public ModelAndView add() {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("good.add");
		mav.addObject("districts", districtService.getAll());
		mav.addObject("repositories", repositoryService.getAll(new RowBounds()));
		return mav;
	}

	@RequestMapping(value = "/save")
	public String save(Good good) {
		goodService.insert(good);
		return "redirect:/good/index";
	}

	@RequestMapping(value = "/edit")
	public ModelAndView edit(int id) {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("good.edit");
		mav.addObject("good", goodService.getById(id));
		mav.addObject("districts", districtService.getAll());
		mav.addObject("repositories", repositoryService.getAll(new RowBounds()));
		return mav;
	}

	@RequestMapping(value = "/update")
	public String update(Good good) {
		goodService.update(good);
		return "redirect:/good/index";
	}

	@RequestMapping(value = "/map")
	public ModelAndView map(int id) {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("good.map");
		mav.addObject("good", goodService.getById(id));
		return mav;
	}

	@RequestMapping(value = "/delete")
	public String deleter(Integer id) {
		goodService.delete(id, null);
		return "redirect:/good/index";
	}
}
